//
//  Contact.m
//  sqlite
//
//  Created by hoho on 14-11-10.
//  Copyright (c) 2014年 hoho. All rights reserved.
//

#import "Contact.h"
#import "DBManager.h"

@implementation Contact{
    DBManager *db;
}

#pragma mark 私有方法

- (DBManager *)dbInstance{
    if(db == nil){
        db = [[DBManager alloc]initWithDatabaseFilename:@"contact.sqlite"];
    }
    return db;
}

#pragma mark 公有方法

- (NSArray *)findAll{
    NSString *sql = @"select * from peopleInfo";
    return [[self dbInstance] loadDataFromDB:sql];
}

- (NSArray *)findOne :(NSUInteger)peopleInfoId{
    NSString *sql = [NSString stringWithFormat:@"select * from peopleInfo where id=%d", peopleInfoId];
    
    return [[self dbInstance] loadDataFromDB:sql];
}

- (NSInteger)del:(NSUInteger)peopleInfoId {
    NSString *sql = [NSString stringWithFormat:@"delete from peopleInfo where id=%d",peopleInfoId];
    [[self dbInstance]executeQuery:sql];
    return [self dbInstance].affectedRows;
}

- (long long)save:(NSInteger)peopleInfoId :(NSString *)contactName :(NSString *)phoneNumber{
    
    NSString *sql;
    if (peopleInfoId == -1) {
        sql = [NSString stringWithFormat:@"insert into peopleInfo values(null, '%@', '%@')", contactName ,phoneNumber];
        [[self dbInstance]executeQuery:sql];
        return [self dbInstance].lastInsertedRowID;
    }else{
        sql = [NSString stringWithFormat:@"update peopleInfo set contact_name='%@', phone_number='%@' where id=%d", contactName, phoneNumber, peopleInfoId];
        [[self dbInstance]executeQuery:sql];
        return [self dbInstance].affectedRows;
    }
    
}


@end
